#import "IUI.h"
#import "MyInfoViewController.h"
#import "fabuViewController.h"
#import "MyFansViewController.h"
#import "GuanzhuViewController.h"
#import "UIImageView+WebCache.h"
#import "shangjiazhiliaoViewController.h"
#import "shangjiaFansViewController.h"
#import "shangjiajianjieViewController.h"
#import "shangjiafabuViewController.h"
#import "AboutUI.h"

@interface IUI (){
    NSDictionary *myInfoDic;
}

@property (nonatomic,strong) UITableView *mainTableView;

@end

@implementation IUI
-(void)myFansFn{
    MyFavListUI*  ui=[[MyFavListUI alloc] init];
    [self.navigationController pushViewController:ui animated:NO];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.separatorStyle=NO;
    self.tableView.contentInset=UIEdgeInsetsMake(0, 0, 600, 0);

    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64-49) style:UITableViewStyleGrouped];
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.tableView setDataSource:self];
    [self.tableView setDelegate:self];
    [self.tableView setBackgroundColor:[UIColor colorWithRed:252/255.0 green:252/255.0 blue:252/255.0 alpha:1.0]];


    

    
    
    
    
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString*  mp=[userDefaults objectForKey:@"mp"];
    if(!(mp&&mp.length>5)){
        //[self.view makeToast:@"请先登录" duration:1.0 position:@"center"];
        LoginViewController *vc = [LoginViewController new];
        vc.hidesBottomBarWhenPushed = YES;
        //[self.navigationController presentViewController:vc animated:YES completion:nil];
        [self.navigationController pushViewController:vc animated:YES];
        self.navigationController.tabBarController.selectedIndex = 0;
        return;
    }
    
    
    if((mp&&mp.length>5)){
        
        
        [loginBtn setTitle:@"退出登录" forState:UIControlStateNormal];
        [loginBtn addTarget:self action:@selector(logoutFn) forControlEvents:UIControlEventTouchUpInside];
        [self loadData];
    }else{
        
        [loginBtn setTitle:@"登录" forState:UIControlStateNormal];
        [loginBtn addTarget:self action:@selector(loginFn) forControlEvents:UIControlEventTouchUpInside];
    }
    
    NSString *userType = [userDefaults objectForKey:@"user_type"];
    if ([userType isEqualToString:@"2"]) {
        UILabel* titleLb=[[UILabel alloc] initWithFrame:CGRectMake(100, 0, 120, 44)];
        titleLb.text=@"商家中心";
        titleLb.backgroundColor=[UIColor clearColor];
        titleLb.textAlignment=NSTextAlignmentCenter;
        titleLb.textColor=[UIColor whiteColor];
        self.navigationItem.titleView=titleLb;
        //self.title = @"商家中心";
    }else{
        UILabel* titleLb=[[UILabel alloc] initWithFrame:CGRectMake(100, 0, 120, 44)];
        titleLb.text=@"个人中心";
        titleLb.backgroundColor=[UIColor clearColor];
        titleLb.textAlignment=NSTextAlignmentCenter;
        titleLb.textColor=[UIColor whiteColor];
        self.navigationItem.titleView=titleLb;
        //self.title = @"个人中心";
    }
    
}
-(void)loginFn{
    NSLog(@"开始登录......");
    LoginViewController*  ui=[[LoginViewController alloc] init];
    [self.navigationController pushViewController:ui animated:NO];
    
}
-(void)logoutFn{
    
    [[EaseMob sharedInstance].chatManager asyncLogoff];
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults removeObjectForKey:@"mp"];
    [userDefaults removeObjectForKey:@"uid"];
    [userDefaults removeObjectForKey:@"pwd"];
    
    [[ApplyViewController shareController] clear];
    [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
    
    
//    if(lb){
//        [lb removeFromSuperview];
//    }
//    int  delta=50;
//    if(loginBtn){
//        [loginBtn removeFromSuperview];
//    }
//    loginBtn=[[UIButton alloc] initWithFrame:CGRectMake(20, SCREEN_HEIGHT-109, 280, 40)];
//    loginBtn.backgroundColor=[UIColor redColor];
//    [loginBtn addTarget:self action:@selector(loginFn) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:loginBtn];
//    //
//    NSLog(@"正在退出...");
//    lb=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 280, 40)];
//    lb.text=@"登   录";
//    lb.textColor=[UIColor whiteColor];
//    lb.textAlignment=NSTextAlignmentCenter;
//    [loginBtn addSubview:lb];
    myInfoDic = [NSDictionary new];
    [self.tableView reloadData];
    [loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    [loginBtn addTarget:self action:@selector(loginFn) forControlEvents:UIControlEventTouchUpInside];
    
    LoginViewController *vc = [LoginViewController new];
    vc.hidesBottomBarWhenPushed = YES;
    //[self.navigationController presentViewController:vc animated:YES completion:nil];
    self.navigationController.tabBarController.selectedIndex = 0;
    [self.navigationController pushViewController:vc animated:YES];
}


-(void)favFn{
    MyFavListUI*  ui=[[MyFavListUI alloc] init];
    [self.navigationController pushViewController:ui animated:NO];
}
-(void)groupFn{
    MyGroupListUI*  ui=[[MyGroupListUI alloc] init];
    [self.navigationController pushViewController:ui animated:NO];
}
-(void)giftFn{
    MyGiftListUI*  ui=[[MyGiftListUI alloc] init];
    [self.navigationController pushViewController:ui animated:NO];
}
-(void)scoreFn{
    MyScoreUI*  ui=[[MyScoreUI alloc] init];
    [self.navigationController pushViewController:ui animated:NO];
}
-(void)mingpianFn{
    NSUserDefaults*  ud=[[NSUserDefaults alloc] init];
    NSString*  mp=[ud objectForKey:@"mp"];
    if(mp&&mp.length>5){
        //MingPianUI* ui=[[MingPianUI alloc] init];
        MyInfoViewController *ui = [MyInfoViewController new];
        ui.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:ui animated:NO];
    }else{
        LoginViewController* ui=[[LoginViewController alloc] init];
        [self.navigationController pushViewController:ui animated:NO];
    }
}
-(void)myAttentionFn{
    NSUserDefaults*  ud=[[NSUserDefaults alloc] init];
    NSString*  mp=[ud objectForKey:@"mp"];
    if(mp&&mp.length>5){
        MyAttentionListUI* ui=[[MyAttentionListUI alloc] init];
        ui.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:ui animated:NO];
    }else{
        LoginViewController* ui=[[LoginViewController alloc] init];
        [self.navigationController pushViewController:ui animated:NO];
    }
    
}

-(void)loadData{
    NSUserDefaults*  ud=[[NSUserDefaults alloc] init];
    NSUserDefaults *accountDefaults = [NSUserDefaults standardUserDefaults];
    NSString* mp_ = [accountDefaults objectForKey:@"phone"];
    //NSString* mp_=[ud objectForKey:@"mp"];
    if (!mp_) {
        return;
    }
    NSLog(@"mp:%@",mp_);
    NSString* loginURL=HOST;
    
        loginURL=[loginURL stringByAppendingString:@"/index.php/appMerchant/loadUserMerchantInfo?merchantId="];

    
    loginURL=[loginURL stringByAppendingFormat:@"%@",[accountDefaults objectForKey:@"uid"]];
    NSLog(@"保存URL.loginURL==%@",loginURL);
    NSURL* url=[[NSURL alloc] initWithString:loginURL];
    ASIFormDataRequest *req=[ASIFormDataRequest requestWithURL:url];
    
    
    [req startSynchronous];
    NSError *error = [req error];
    
    
    if (!error) {
        AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
        [MBProgressHUD hideHUDForView:app.window animated:YES];
        
        NSString *response = [req responseString];
        NSLog(@"保存返回结果%@",response);
        myInfoDic=[response JSONValue];
        NSString* uid=[myInfoDic objectForKey:@"uid"];
        NSLog(@"ID%@",uid);
        
        myInfoDic = [self removeNullFrom:myInfoDic];
        NSUserDefaults *accountDefaults = [NSUserDefaults standardUserDefaults];
        [accountDefaults setObject:myInfoDic forKey:@"myInfoDic"];
        
        [self.tableView reloadData];
        //[self performSelectorOnMainThread:@selector(finishLoadMyInfoFn) withObject:nil waitUntilDone:YES];
    }else{
        NSLog(@"move failed:%@", [error localizedDescription]);
    }
}

- (NSObject *)removeNullFrom:(NSObject *)object
{
    NSObject *objResult = nil;
    NSMutableArray *marrSearch = nil;
    if ([object isKindOfClass:NSNull.class]) {
        return nil;
    }
    else if ([object isKindOfClass:NSArray.class]) {
        objResult = [NSMutableArray arrayWithArray:(NSArray *)object];
        marrSearch = [NSMutableArray arrayWithObject:objResult];
    }
    else if ([object isKindOfClass:NSDictionary.class]) {
        objResult = [NSMutableDictionary dictionaryWithDictionary:(NSDictionary *)object];
        marrSearch = [NSMutableArray arrayWithObject:objResult];
    }
    else {
        return object;
    }
    while (marrSearch.count > 0) {
        NSObject *header = marrSearch[0];
        if ([header isKindOfClass:NSMutableDictionary.class]) {
            // 遍历这个字典
            NSMutableDictionary *mdicTemp = (NSMutableDictionary *)header;
            for (NSString *strKey in mdicTemp.allKeys) {
                NSObject *objTemp = mdicTemp[strKey];
                // 将NSDictionary替换为NSMutableDictionary
                if ([objTemp isKindOfClass:NSDictionary.class]) {
                    NSMutableDictionary *mdic = [NSMutableDictionary dictionaryWithDictionary:(NSDictionary *)objTemp];
                    mdicTemp[strKey] = mdic;
                    [marrSearch addObject:mdic];
                }
                // 将NSArray替换为NSMutableArray
                else if ([objTemp isKindOfClass:NSArray.class]) {
                    NSMutableArray *marr = [NSMutableArray arrayWithArray:(NSArray *)objTemp];
                    mdicTemp[strKey] = marr;
                    [marrSearch addObject:marr];
                }
                // 删除NSNull
                else if ([objTemp isKindOfClass:NSNull.class]) {
                    mdicTemp[strKey] = nil;
                }
            }
        }
        else if ([header isKindOfClass:NSMutableArray.class]) {
            // 遍历这个数组
            NSMutableArray *marrTemp = (NSMutableArray *)header;
            for (int i = marrTemp.count-1; i >= 0; i--) {
                NSObject *objTemp = marrTemp[i];
                // 将NSDictionary替换为NSMutableDictionary
                if ([objTemp isKindOfClass:NSDictionary.class]) {
                    NSMutableDictionary *mdic = [NSMutableDictionary dictionaryWithDictionary:(NSDictionary *)objTemp];
                    [marrTemp replaceObjectAtIndex:i withObject:mdic];
                    [marrSearch addObject:mdic];
                }
                // 将NSArray替换为NSMutableArray
                else if ([objTemp isKindOfClass:NSArray.class]) {
                    NSMutableArray *marr = [NSMutableArray arrayWithArray:(NSArray *)objTemp];
                    [marrTemp replaceObjectAtIndex:i withObject:marr];
                    [marrSearch addObject:marr];
                }
                // 删除NSNull
                else if ([objTemp isKindOfClass:NSNull.class]) {
                    [marrTemp removeObjectAtIndex:i];
                }
            }
        }
        else {
            // 到这里就出错了
        }
        [marrSearch removeObjectAtIndex:0];
    }
    return objResult;
}

#pragma mark UITableViewDelegate/UITableViewDataSource

/**
 *  每个cell有多少行
 */
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
}


/**
 *  有多少个section
 */
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 5;
}

/**
 *  section的title
 */
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    
    return nil;
}

/**
 *  header的距离
 */
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return CGFLOAT_MIN;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section == 4) {
        return 200;
    }
    return 10;
}

/**
 *  row的高度
 */
-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 80;
    }
    return 34;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (section == 4) {
        UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 200)];
        loginBtn=[[UIButton alloc] initWithFrame:CGRectMake(20, 100, 280, 40)];
        loginBtn.backgroundColor=[UIColor redColor];
        
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        NSString*  mp=[userDefaults objectForKey:@"mp"];
        if((mp&&mp.length>5)){
            [loginBtn setTitle:@"退出登录" forState:UIControlStateNormal];
            [loginBtn addTarget:self action:@selector(logoutFn) forControlEvents:UIControlEventTouchUpInside];
        }else{
            [loginBtn setTitle:@"登录" forState:UIControlStateNormal];
            [loginBtn addTarget:self action:@selector(loginFn) forControlEvents:UIControlEventTouchUpInside];
        }
        
        [bgView addSubview:loginBtn];
        return bgView;
    }
    return nil;
}

/**
 *  cell的属性
 */
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [UITableViewCell new];
    
    
    
    if (indexPath.section == 0) {
        UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(30, 10, 60, 60)];
        imgView.backgroundColor = [UIColor lightGrayColor];
        if ((![[myInfoDic objectForKey:@"avatar"] isEqual:[NSNull null]])&&[[myInfoDic objectForKey:@"avatar"] rangeOfString:@"http"].location != NSNotFound) {
            [imgView setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",[myInfoDic objectForKey:@"avatar"]]] placeholderImage:[UIImage new]];
        }else
            [imgView setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HOST,[myInfoDic objectForKey:@"avatar"]]] placeholderImage:[UIImage new]];
        
        [cell addSubview:imgView];
        
        NSString *str_qm = [myInfoDic objectForKey:@"qm"];
        NSString *str_name = [myInfoDic objectForKey:@"nickname"];
        
        if ([str_qm isEqual:[NSNull null]]||str_qm.length == 0) {
            str_qm = @"";
        }
        if ([str_name isEqual:[NSNull null]]||str_name.length == 0) {
            str_name = @"";
        }
        
        UILabel *nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(110, 10, 200, 30)];
        nameLabel.text = [NSString stringWithFormat:@"%@",str_name];
        nameLabel.font = [UIFont systemFontOfSize:20];
        [cell addSubview:nameLabel];
        
        UILabel *nameLabel2 = [[UILabel alloc]initWithFrame:CGRectMake(110, 50, 200, 15)];
        NSString *str = [NSString stringWithFormat:@"%@",str_qm];
        nameLabel2.text = [NSString stringWithFormat:@"%@",str.length == 0?@"":str];
        nameLabel2.font = [UIFont systemFontOfSize:13];
        [cell addSubview:nameLabel2];
        
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
    }else{
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        NSString *userType = [userDefaults objectForKey:@"user_type"];
        NSArray *array;
        if ([userType isEqualToString:@"2"]) {
            array = @[@"简介",@"发布",@"粉丝",@"关于夜猫"];
        }else{
            array = @[@"发布",@"关注",@"粉丝",@"关于夜猫"];
        }
        
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(30, 10, 100, 14)];
        label.text = [array objectAtIndex:indexPath.section-1];
        [cell addSubview:label];
        
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    
    return cell;
}

/**
 *  点击事件
 */
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString*  mp=[userDefaults objectForKey:@"mp"];
    if(!(mp&&mp.length>5)){
        [self.view makeToast:@"请先登录" duration:1.0 position:@"center"];
        LoginViewController *vc = [LoginViewController new];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
        return;
    }
    
    
    NSString *userType = [userDefaults objectForKey:@"user_type"];
    NSArray *array;
    if ([userType isEqualToString:@"2"]) {
        if (indexPath.section == 0) {
            //MingPianUI *vc = [MingPianUI new];
            shangjiazhiliaoViewController *vc = [shangjiazhiliaoViewController new];
            vc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
        }else if(indexPath.section == 1){
            shangjiajianjieViewController *vc = [shangjiajianjieViewController new];
            vc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
        }else if(indexPath.section == 2){
            shangjiafabuViewController *vc = [shangjiafabuViewController new];
            vc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
        }else if(indexPath.section == 3){
            shangjiaFansViewController *vc = [shangjiaFansViewController new];
            vc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
        }else if (indexPath.section == 4){
            AboutUI *vc = [AboutUI new];
            vc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
        }
    }else{
    
    if (indexPath.section == 0) {
        //MingPianUI *vc = [MingPianUI new];
        MyInfoViewController *vc = [MyInfoViewController new];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }else if(indexPath.section == 1){
        fabuViewController *vc = [fabuViewController new];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }else if(indexPath.section == 2){
        GuanzhuViewController *vc = [GuanzhuViewController new];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }else if(indexPath.section == 3){
        MyFansViewController *vc = [MyFansViewController new];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }else if (indexPath.section == 4){
        AboutUI *vc = [AboutUI new];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}


@end
